/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rysi.productos.oad;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import rysi.productos.modelo.Usuario;
import rysi.productos.modelo.DetalleDeCompra;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import rysi.productos.modelo.Compra;
import rysi.productos.oad.exceptions.IllegalOrphanException;
import rysi.productos.oad.exceptions.NonexistentEntityException;

/**
 *
 * @author jaguilar
 */
public class CompraJpaController implements Serializable {

    public CompraJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Compra compra) {
        if (compra.getDetalleDeCompraCollection() == null) {
            compra.setDetalleDeCompraCollection(new ArrayList<DetalleDeCompra>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Usuario idCliente = compra.getIdCliente();
            if (idCliente != null) {
                idCliente = em.getReference(idCliente.getClass(), idCliente.getIdUsuario());
                compra.setIdCliente(idCliente);
            }
            Collection<DetalleDeCompra> attachedDetalleDeCompraCollection = new ArrayList<DetalleDeCompra>();
            for (DetalleDeCompra detalleDeCompraCollectionDetalleDeCompraToAttach : compra.getDetalleDeCompraCollection()) {
                detalleDeCompraCollectionDetalleDeCompraToAttach = em.getReference(detalleDeCompraCollectionDetalleDeCompraToAttach.getClass(), detalleDeCompraCollectionDetalleDeCompraToAttach.getDetalleDeCompraPK());
                attachedDetalleDeCompraCollection.add(detalleDeCompraCollectionDetalleDeCompraToAttach);
            }
            compra.setDetalleDeCompraCollection(attachedDetalleDeCompraCollection);
            em.persist(compra);
            if (idCliente != null) {
                idCliente.getCompraCollection().add(compra);
                idCliente = em.merge(idCliente);
            }
            for (DetalleDeCompra detalleDeCompraCollectionDetalleDeCompra : compra.getDetalleDeCompraCollection()) {
                Compra oldCompraOfDetalleDeCompraCollectionDetalleDeCompra = detalleDeCompraCollectionDetalleDeCompra.getCompra();
                detalleDeCompraCollectionDetalleDeCompra.setCompra(compra);
                detalleDeCompraCollectionDetalleDeCompra = em.merge(detalleDeCompraCollectionDetalleDeCompra);
                if (oldCompraOfDetalleDeCompraCollectionDetalleDeCompra != null) {
                    oldCompraOfDetalleDeCompraCollectionDetalleDeCompra.getDetalleDeCompraCollection().remove(detalleDeCompraCollectionDetalleDeCompra);
                    oldCompraOfDetalleDeCompraCollectionDetalleDeCompra = em.merge(oldCompraOfDetalleDeCompraCollectionDetalleDeCompra);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Compra compra) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Compra persistentCompra = em.find(Compra.class, compra.getIdCompra());
            Usuario idClienteOld = persistentCompra.getIdCliente();
            Usuario idClienteNew = compra.getIdCliente();
            Collection<DetalleDeCompra> detalleDeCompraCollectionOld = persistentCompra.getDetalleDeCompraCollection();
            Collection<DetalleDeCompra> detalleDeCompraCollectionNew = compra.getDetalleDeCompraCollection();
            List<String> illegalOrphanMessages = null;
            for (DetalleDeCompra detalleDeCompraCollectionOldDetalleDeCompra : detalleDeCompraCollectionOld) {
                if (!detalleDeCompraCollectionNew.contains(detalleDeCompraCollectionOldDetalleDeCompra)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain DetalleDeCompra " + detalleDeCompraCollectionOldDetalleDeCompra + " since its compra field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idClienteNew != null) {
                idClienteNew = em.getReference(idClienteNew.getClass(), idClienteNew.getIdUsuario());
                compra.setIdCliente(idClienteNew);
            }
            Collection<DetalleDeCompra> attachedDetalleDeCompraCollectionNew = new ArrayList<DetalleDeCompra>();
            for (DetalleDeCompra detalleDeCompraCollectionNewDetalleDeCompraToAttach : detalleDeCompraCollectionNew) {
                detalleDeCompraCollectionNewDetalleDeCompraToAttach = em.getReference(detalleDeCompraCollectionNewDetalleDeCompraToAttach.getClass(), detalleDeCompraCollectionNewDetalleDeCompraToAttach.getDetalleDeCompraPK());
                attachedDetalleDeCompraCollectionNew.add(detalleDeCompraCollectionNewDetalleDeCompraToAttach);
            }
            detalleDeCompraCollectionNew = attachedDetalleDeCompraCollectionNew;
            compra.setDetalleDeCompraCollection(detalleDeCompraCollectionNew);
            compra = em.merge(compra);
            if (idClienteOld != null && !idClienteOld.equals(idClienteNew)) {
                idClienteOld.getCompraCollection().remove(compra);
                idClienteOld = em.merge(idClienteOld);
            }
            if (idClienteNew != null && !idClienteNew.equals(idClienteOld)) {
                idClienteNew.getCompraCollection().add(compra);
                idClienteNew = em.merge(idClienteNew);
            }
            for (DetalleDeCompra detalleDeCompraCollectionNewDetalleDeCompra : detalleDeCompraCollectionNew) {
                if (!detalleDeCompraCollectionOld.contains(detalleDeCompraCollectionNewDetalleDeCompra)) {
                    Compra oldCompraOfDetalleDeCompraCollectionNewDetalleDeCompra = detalleDeCompraCollectionNewDetalleDeCompra.getCompra();
                    detalleDeCompraCollectionNewDetalleDeCompra.setCompra(compra);
                    detalleDeCompraCollectionNewDetalleDeCompra = em.merge(detalleDeCompraCollectionNewDetalleDeCompra);
                    if (oldCompraOfDetalleDeCompraCollectionNewDetalleDeCompra != null && !oldCompraOfDetalleDeCompraCollectionNewDetalleDeCompra.equals(compra)) {
                        oldCompraOfDetalleDeCompraCollectionNewDetalleDeCompra.getDetalleDeCompraCollection().remove(detalleDeCompraCollectionNewDetalleDeCompra);
                        oldCompraOfDetalleDeCompraCollectionNewDetalleDeCompra = em.merge(oldCompraOfDetalleDeCompraCollectionNewDetalleDeCompra);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = compra.getIdCompra();
                if (findCompra(id) == null) {
                    throw new NonexistentEntityException("The compra with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Compra compra;
            try {
                compra = em.getReference(Compra.class, id);
                compra.getIdCompra();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The compra with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<DetalleDeCompra> detalleDeCompraCollectionOrphanCheck = compra.getDetalleDeCompraCollection();
            for (DetalleDeCompra detalleDeCompraCollectionOrphanCheckDetalleDeCompra : detalleDeCompraCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Compra (" + compra + ") cannot be destroyed since the DetalleDeCompra " + detalleDeCompraCollectionOrphanCheckDetalleDeCompra + " in its detalleDeCompraCollection field has a non-nullable compra field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Usuario idCliente = compra.getIdCliente();
            if (idCliente != null) {
                idCliente.getCompraCollection().remove(compra);
                idCliente = em.merge(idCliente);
            }
            em.remove(compra);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Compra> findCompraEntities() {
        return findCompraEntities(true, -1, -1);
    }

    public List<Compra> findCompraEntities(int maxResults, int firstResult) {
        return findCompraEntities(false, maxResults, firstResult);
    }

    private List<Compra> findCompraEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Compra.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Compra findCompra(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Compra.class, id);
        } finally {
            em.close();
        }
    }

    public int getCompraCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Compra> rt = cq.from(Compra.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
